package com.white.FalseWorld;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.gyf.immersionbar.ImmersionBar;
import com.white.FalseWorld.adapters.FriendCircleAdapter;
import com.white.FalseWorld.beans.FriendCircleBean;
import com.white.FalseWorld.interfaces.OnPraiseOrCommentClickListener;
import com.white.FalseWorld.others.DataCenter;
import com.white.FalseWorld.others.FriendsCircleAdapterDivideLine;
import com.white.FalseWorld.others.GlideSimpleTarget;
import com.white.FalseWorld.utils.Utils;
import com.white.FalseWorld.widgets.EmojiPanelView;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

import ch.ielse.view.imagewatcher.ImageWatcher;
import io.reactivex.Single;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static java.sql.DriverManager.getConnection;

/**
 * 作者：white
 * 时间：2020/10/1.
 */
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener,
        OnPraiseOrCommentClickListener, ImageWatcher.OnPictureLongPressListener, ImageWatcher.Loader {

    private SwipeRefreshLayout mSwipeRefreshLayout,swpie_xiaoshi;
    private Disposable mDisposable;
    private FriendCircleAdapter mFriendCircleAdapter;
    private ImageWatcher mImageWatcher;
    private EmojiPanelView mEmojiPanelView;
    RecyclerView recyclerView;
    RelativeLayout title_Bar;
    private TextView wx_pyq_title,wx_name;
    private ImageView wx_pyq_xj,img_back,wx_touxiang;


    private int imgWidth;
    private int imgHeight;
    private float mY;
    private float mX,m,d,x,y;
    private int ScreenX;
    private int ScreenY;
    private String user;
    private String temp_wx_pyq_picture,temp_user,temp_headpicture;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.activity_main);

        ImmersionBar.with(this).init();//一键透明状态栏

        /**
         * 获取登录页面传过来的账号[微信号]
         * 利用账号读取数据库相关信息（名字，头像地址，背景地址）
         */
        user = getIntent().getStringExtra("user");

        System.out.println( "传过来的微信号："+user );

        mEmojiPanelView = findViewById(R.id.emoji_panel_view);
        mEmojiPanelView.initEmojiPanel(DataCenter.emojiDataSources);
        mSwipeRefreshLayout = findViewById(R.id.swpie_refresh_layout);

         recyclerView = findViewById(R.id.recycler_view);
        mSwipeRefreshLayout.setOnRefreshListener(this);

//        findViewById(R.id.img_back).setOnClickListener(v ->
//                startActivity(new Intent(MainActivity.this, EmojiPanelActivity.class)));

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Glide.with(MainActivity.this).resumeRequests();
                } else {
                    Glide.with(MainActivity.this).pauseRequests();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });


        mImageWatcher = findViewById(R.id.image_watcher);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new FriendsCircleAdapterDivideLine());

        recyclerView.setLayoutManager(new LinearLayoutManager(this));


        mFriendCircleAdapter = new FriendCircleAdapter(this, recyclerView, mImageWatcher);
        recyclerView.setAdapter(mFriendCircleAdapter);
        mImageWatcher.setTranslucentStatus(Utils.calcStatusBarHeight(this));
        mImageWatcher.setErrorImageRes(R.mipmap.error_picture);
        mImageWatcher.setOnPictureLongPressListener(this);
        mImageWatcher.setLoader(this);
        Utils.showSwipeRefreshLayout(mSwipeRefreshLayout, this::asyncMakeData);


        //*******************************************
        title_Bar=findViewById( R.id.title_Bar );
        wx_pyq_title=findViewById( R.id.wx_pyq_title );
        wx_pyq_xj=findViewById( R.id.wx_pyq_xj );
        img_back=findViewById( R.id.img_back );
        wx_name=findViewById( R.id.wx_name );
        wx_touxiang=findViewById( R.id.wx_touxiang );

        /* 取得屏幕对象 */
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        /* 取得屏幕解析像素 */
        ScreenX = dm.widthPixels;
        ScreenY = dm.heightPixels;

        pyq_query_mysql_init();
        if(wx_name!=null){

        }else{
            System.out.println( "空"+user );
        }

        img_back.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        } );



    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                Bundle data = msg.getData();
                String user = data.getString("user");
                String headpicture = data.getString("headpicture");
                String wx_pyq_picture = data.getString("wx_pyq_picture");
                //设置UI
                Glide.with(getApplicationContext())
                        .asBitmap()
                        .load(wx_pyq_picture)
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                Drawable drawable = new BitmapDrawable(resource);
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                    title_Bar.setBackground(drawable);
                                }
                            }

                        });
                Glide.with(getApplicationContext())
                        .asBitmap()
                        .load(headpicture)
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                Drawable drawable = new BitmapDrawable(resource);
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                    wx_touxiang.setImageDrawable(drawable);
                                }
                            }

                        });

                wx_name.setText( user );
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) wx_name
                        .getLayoutParams();
                params.rightMargin=10;
                wx_name.setLayoutParams( params );
                System.out.println( "名字："+temp_user+"头像地址："+temp_headpicture+"  背景地址"+ temp_wx_pyq_picture);
               // Toast.makeText(getApplicationContext(),"请求资源成功",Toast.LENGTH_LONG).show();
            } else if (msg.what ==0) {
                Toast.makeText(getApplicationContext(),"请求资源不成功",Toast.LENGTH_LONG).show();
            }
        }
    };

    private void pyq_query_mysql_data() {

           }

    private void pyq_query_mysql_init() {
        new Thread( new Runnable() {
            @Override
            public void run() {
                try {
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection cn= getConnection( getString( R.string.mysql_address ),getString( R.string.mysql_username ),getString( R.string.mysql_password ));
                    System.out.println("连接数据库成功");
                    String sql="SELECT * FROM personals WHERE user_wx= '"+user+"'";
                    Statement st=(Statement)cn.createStatement();
                    ResultSet rs=st.executeQuery(sql);
                    while(rs.next()){
                        temp_user=rs.getString("user");
                        temp_headpicture=rs.getString( "headpicture" );
                        temp_wx_pyq_picture=rs.getString( "wx_pyq_picture" );
                        System.out.println( "11111名字："+temp_user+"头像地址："+temp_headpicture+"  背景地址"+ temp_wx_pyq_picture);
                    }
                    System.out.println( "2222名字："+temp_user+"头像地址："+temp_headpicture+"  背景地址"+ temp_wx_pyq_picture);
                    cn.close();
                    st.close();
                    rs.close();
                    Message msg = new Message();
                    Bundle data = new Bundle();

                    //将获取到的String装载到msg中
                    data.putString("user", temp_user);
                    data.putString("headpicture", getString( R.string.url_prefix )+temp_headpicture);
                    data.putString("wx_pyq_picture", getString( R.string.url_prefix )+temp_wx_pyq_picture);
                    msg.setData(data);
                    msg.what = 1;
                    //发消息到主线程
                    handler.sendMessage(msg);
                    pyq_query_mysql_data();
                    System.out.println("连接数据库操作执行完毕");
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        } ).start();
    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        imgWidth = (int) event.getX();
        imgHeight =300;

        // TODO Auto-generated method stub
        /*获取手触屏的位置*/
        m=event.getX();
        d=event.getY();
        x = event.getX()-45;
        y = event.getY()-160;

        /*默认微调图片与指针的相对位置*/
        mX=x-(imgWidth/2);
        mY=y-(imgHeight/2);

        /*分开处理触摸的时间*/
        switch (event.getAction()) {

            /*点屏幕*/
            case MotionEvent.ACTION_DOWN  :

//                title_Bar.setLayoutParams(new
//                        AbsoluteLayout.LayoutParams
//                        (imgWidth, imgHeight, (int)mX,(int)mY));

                break;
            /*移动位置*/
            case MotionEvent.ACTION_MOVE  :

//                title_Bar.setLayoutParams(new
//                        AbsoluteLayout.LayoutParams
//                        (imgWidth, imgHeight, (int)mX,(int)mY));
                moveViewWithFinger(title_Bar,event.getX(),event.getRawX(),event.getRawY());

                break;

            /*离开屏幕*/
            case MotionEvent.ACTION_UP  :

//                title_Bar.setLayoutParams(new
//                        AbsoluteLayout.LayoutParams
//                        (imgWidth, imgHeight, (int)mX,(int)mY));

                break;

            default:
                break;
        }

        return true;
    }
    private void moveViewWithFinger(RelativeLayout view, float getx,float rawX, float rawY) {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view
                .getLayoutParams();

        int c=(int) rawY - 300 / 2;

        System.out.println( "  背景地址"+ temp_wx_pyq_picture);

        /*
        * 判断，当头部布局到达180停止往上滑，并且显示["朋友圈"]文字，背景颜色为灰色
        * 当头部布局达到700停止往下滑,view的背景照片恢复正常  (未完成)
        * */
        if (c<=180){
            wx_pyq_title.setVisibility( View.VISIBLE );
            view.setBackgroundColor( Color.parseColor( "#efefef" ));
            img_back.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(),R.drawable.fx_b ));
            wx_pyq_xj.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(),R.drawable.xj_b ));
        }else if (c>=850){
            wx_pyq_title.setVisibility( View.INVISIBLE );
            img_back.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(),R.drawable.fx_w ));
            wx_pyq_xj.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(),R.drawable.xj_w ));
            Glide.with(MainActivity.this)
                    .asBitmap()
                    .load(getString( R.string.url_prefix )+temp_wx_pyq_picture)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                            Drawable drawable = new BitmapDrawable(resource);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                title_Bar.setBackground(drawable);
                            }
                        }

                    });
        }else{

            params.height = (int) rawY - 300 / 2;
            wx_pyq_title.setVisibility( View.INVISIBLE );
            img_back.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(),R.drawable.fx_w ));
            wx_pyq_xj.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(),R.drawable.xj_w ));
            view.setLayoutParams(params);
            Glide.with(MainActivity.this)
                    .asBitmap()
                    .load(getString( R.string.url_prefix )+temp_wx_pyq_picture)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                            Drawable drawable = new BitmapDrawable(resource);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                title_Bar.setBackground(drawable);
                            }
                        }

                    });
        }
    }

    private void asyncMakeData() {
        mDisposable = Single.create((SingleOnSubscribe<List<FriendCircleBean>>) emitter ->
                emitter.onSuccess(DataCenter.makeFriendCircleBeans(this)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((friendCircleBeans, throwable) -> {
                    Utils.hideSwipeRefreshLayout(mSwipeRefreshLayout);
                    if (friendCircleBeans != null && throwable == null) {
                        mFriendCircleAdapter.setFriendCircleBeans(friendCircleBeans);
                    }
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    @Override
    public void onRefresh() {
        asyncMakeData();
    }

    @Override
    public void onPraiseClick(int position) {
        Toast.makeText(this, "You Click Praise!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCommentClick(int position) {
//        Toast.makeText(this, "you click comment", Toast.LENGTH_SHORT).show();
        mEmojiPanelView.showEmojiPanel();
    }

    @Override
    public void onBackPressed() {
        if (!mImageWatcher.handleBackPressed()) {
            super.onBackPressed();
        }
    }

    @Override
    public void onPictureLongPress(ImageView v, String url, int pos) {

    }


    @Override
    public void load(Context context, String url, ImageWatcher.LoadCallback lc) {
        Glide.with(context).asBitmap().load(url).into(new GlideSimpleTarget(lc));
    }
}
